package foodmaterial.config;

import com.alibaba.druid.pool.DruidDataSource;
import foodmaterial.entity.CompanyDatabase;

import javax.sql.DataSource;
import java.util.Map;

public class DataSourceUtils {

    public static DruidDataSource createDataSource(String username,String password,
                                              String driver,String url) {
        DruidDataSource dynamicDataSource = new DruidDataSource();
        dynamicDataSource.setDriverClassName(driver);
        dynamicDataSource.setUrl(url);
        dynamicDataSource.setUsername(username);
        dynamicDataSource.setPassword(password);
        return dynamicDataSource ;
    }

    public static DruidDataSource createDataSource(CompanyDatabase db) {
        DruidDataSource dynamicDataSource = new DruidDataSource();
        dynamicDataSource.setDriverClassName(db.getDriverName());
        StringBuilder url = new StringBuilder() ;
        url.append("jdbc:mysql://");
        url.append(db.getIp()).append(':');
        url.append(db.getPort()).append('/').append(db.getDatabase());
        url.append("?userSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai");
        dynamicDataSource.setUrl(url.toString());
        dynamicDataSource.setUsername(db.getUsername());
        dynamicDataSource.setPassword(db.getPassword());
        dynamicDataSource.setMaxWait(db.getMaxWait());
        dynamicDataSource.setInitialSize(db.getInitialSize());
        dynamicDataSource.setMinIdle(db.getMinIdle());
        dynamicDataSource.setMaxActive(db.getMaxActive());
        return dynamicDataSource ;
    }

    public static void addDataSource(String name, DataSource dataSource) {
        Map<Object, Object> dataSourceMap = DynamicDataSource.getInstance().getDataSourceMap();
        if (dataSourceMap.containsKey(name)) return ;//数据源已经存在不需要再添加
        dataSourceMap.put(name, dataSource);
        DynamicDataSource.getInstance().setTargetDataSources(dataSourceMap);
    }

    public static void removeDataSource(String name) {
        Map<Object, Object> dataSourceMap = DynamicDataSource.getInstance().getDataSourceMap();
        ((DruidDataSource)dataSourceMap.remove(name)).close();
        DynamicDataSource.getInstance().setTargetDataSources(dataSourceMap);
    }
}
